<?php
namespace app\common\model;

use think\Db;

class FormFieldModel extends BaseModel
{
    protected $name = 'form_field'; //定义表单表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    //类型自动转换
    protected $type = [
        'set'      => 'json',
        'validate' => 'json',
    ];
    /*读取器*/

    /*修改器*/
    protected function setFieldNameAttr($value)
    {
        return strtolower($value);
    }

    /**
     * 获取验证器规则
     */
    public function getValidateRule()
    {
        $validateRule = [
            'require'     => '必填',
            'number'      => '数字',
            'float'       => '浮点数',
            'email'       => 'email',
            'date'        => '日期',
            'alpha'       => '字母',
            'alphaNum'    => '字母数字',
            'alphaDash'   => '字母数字下划线',
            'url'         => '超级链接',
            'chs'         => '汉字',
            'chsAlpha'    => '汉字字母',
            'chsAlphaNum' => '汉字字母数字',
            'chsDash'     => '汉字字母数字下划线破折号',
        ];
        return $validateRule;
    }

    /**
     * 添加字段
     */
    public function addData($data)
    {
        if (empty($data['form_id'])) {
            $this->error = '表单不明确！';
            return false;
        }
        //获取对应表名
        $tableName = Db::table('form')->where('form_id', $data['form_id'])->value('table_name');
        $tableName = config('database.prefix') . 'form_' . $tableName;
        //获取字段名
        $fieldName = $data['field_name']; //字段名
        $fields    = array_keys(\think\Db::getFields($tableName));
        if (in_array($fieldName, $fields)) {
            $this->error = '该字段名已存在!';
            return false;
        }
        switch ($data['field_type']) {
            case 'input': //文本框
                $length = $data['set']['length'];
                $sql    = "ALTER TABLE {$tableName} ADD {$fieldName} VARCHAR({$length}) NOT NULL DEFAULT '' COMMENT '{$data['field_title']}'";
                break;
            case 'box':
                $set    = $data['set'];
                $length = $data['set']['length'];
                if ($set['field_type'] == 'vachar') {
                    if (empty($length)) $length = '255';
                    $sql = "ALTER TABLE {$tableName} ADD {$fieldName}  VARCHAR({$length}) NOT NULL DEFAULT ''";
                } else {
                    if (empty($length)) $length = 4;
                    $fieldSet = " {$set['field_type']}({$length}) NOT NULL DEFAULT 0";
                    $sql      = "ALTER TABLE {$tableName} ADD {$fieldName} {$fieldSet} ";
                }
                break;
            case 'number':
                $set = $data['set'];
                if ($set['field_type'] == 'decimal') {
                    $e        = isset($set['num_decimal']) ? $set['num_decimal'] : 0;
                    $fieldSet = " DECIMAL({$set['num_integer']},{$e}) NOT NULL DEFAULT 0";
                } else {
                    $fieldSet = " {$set['field_type']}({$set['num_integer']}) NOT NULL DEFAULT 0";
                }
                $sql = "ALTER TABLE {$tableName} ADD {$fieldName} {$fieldSet} ";
                break;
            case 'textarea':
                $sql = "ALTER TABLE {$tableName} ADD {$fieldName}  VARCHAR(255) NOT NULL DEFAULT '' ";
                break;
            default:
                $sql = '';
                break;
        }
        if (empty($sql)) {
            $this->error('字段创建失败!');
            return false;
        }
        Db::execute($sql);
        $this->isUpdate(false)->allowField(true)->save($data);
        return true;
    }

    /**
     * 删除字段数据
     */
    public function delData($fieldId)
    {
        $info = $this->get($fieldId);
        if (!$info) {
            $this->error = '未找到字段信息';
            return false;
        }
        $tableName = Db::table('form')->where('form_id', $info['form_id'])->value('table_name');
        $tableName = config('database.prefix') . 'form_' . $tableName; //表名
        $fields    = array_keys(\think\Db::getFields($tableName));
        if (in_array($info['field_name'], $fields)) { //先删除表字段
            $sql = "ALTER TABLE " . $tableName . " DROP " . $info['field_name'];
            Db::execute($sql);
        }
        $this->destroy($fieldId);
        return true;
    }

    /**
     * 文本框
     * @param $field
     * @return string
     */
    public function _input($field)
    {
        $set = $field['set'];
        $h   = '<input type="text" name="' . $field['field_name'] . '" value="' . $set['default'] . '" />';
        return $h . PHP_EOL;
    }

    /**
     * 数字框
     * @param $field
     * @return string
     */
    public function _number($field)
    {
        $set = $field['set'];
        $h   = '<input type="text" name="' . $field['field_name'] . '" value="' . $set['default'] . '" />';
        return $h . PHP_EOL;
    }

    /**
     * 多行文本框
     * @param $field
     * @return string
     */
    public function _textarea($field)
    {
        $set = $field['set'];
        $h   = "&lt;textarea name=\"{$field['field_name']}\"&gt;{$set['default']}&lt;/textarea&gt;";
        return $h . PHP_EOL;
    }

    /**
     * 选项
     * @param $field
     * @return string
     */
    public function _box($field)
    {
        $set = $field['set'];
        //表单值
        $_v      = explode(",", $set['options']);
        $options = [];
        foreach ($_v as $p) {
            $p              = explode("|", $p);
            $options[$p[0]] = $p[1];
        }
        $h = '';
        //select添加select
        if ($set['form_type'] == 'select') {
            $h .= "<select name=\"{$field['field_name']}\">" . PHP_EOL;
        }
        foreach ($options as $v => $text) {
            switch ($set['form_type']) {
                case "radio" :
                    $checked = $set['default'] == $v ? 'checked' : '';
                    $h .= "<label class=\"radio-inline\"><input type='radio' name=\"{$field['field_name']}\" value=\"{$v}\" {$checked}/> {$text}</label>" . PHP_EOL;
                    break;
                case "checkbox" :
                    $checked = in_array($v, $set['default']) ? 'checked=""' : '';
                    $h .= "<label class=\"checkbox-inline\"><input type='checkbox' name=\"{$field['field_name']}[]\" value=\"{$v}\" {$checked}/> {$text}</label>" . PHP_EOL;
                    break;
                case "select" :
                    $selected = $set['default'] == $v ? 'selected=""' : "";
                    $h .= "<option name=\"{$field['field_name']}\" value=\"{$v}\" {$selected}> {$text}</option>" . PHP_EOL;
                    break;
            }
        }
        if ($set['form_type'] == 'select') {
            $h .= "</select>" . PHP_EOL;
        }
        return $h;
    }
}




